// 页面加载完成后初始化 UI 和功能
document.addEventListener('DOMContentLoaded', function() {
    // 检测是否在标签页中打开
    const isInTab = window.location.protocol.includes('chrome-extension');

    // 如果在标签页中打开，就应用全屏样式
    if (isInTab) {
        document.body.classList.add('in-tab');

        // 在全屏模式下，同时显示编辑器和预览区域
        const svgInput = document.getElementById('svg-input');
        const svgOutput = document.getElementById('svg-output');

        if (svgInput) svgInput.classList.remove('hidden');
        if (svgOutput) svgOutput.classList.remove('hidden');

        // 监听代码变化，进行实时预览
        const svgCode = document.getElementById('svg-code');
        if (svgCode) {
            svgCode.addEventListener('input', function() {
                const code = this.value.trim();
                if (code) {
                    renderSVG(code);
                    // 保存到存储
                    chrome.storage.local.set({ svgCode: code });
                }
            });
        }
    }

    // DOM Elements
    const svgCode = document.getElementById('svg-code');
    const svgOutput = document.getElementById('svg-output');
    const svgInput = document.getElementById('svg-input');
    const previewBtn = document.getElementById('preview-btn');
    const pasteBtn = document.getElementById('paste-btn');
    const copyBtn = document.getElementById('copy-btn');
    const clearBtn = document.getElementById('clear-btn');
    const notification = document.getElementById('notification');
    const tabs = document.querySelectorAll('.tab');
    const zoomIn = document.getElementById('zoom-in');
    const zoomOut = document.getElementById('zoom-out');
    const zoomReset = document.getElementById('zoom-reset');
    const positionReset = document.getElementById('position-reset');

    // 获取本地化文本的辅助函数
    function getLocalizedMessage(key) {
        // 优先使用自定义的 i18n 函数
        if (window.i18n && typeof window.i18n.getTranslation === 'function') {
            return window.i18n.getTranslation(key);
        }
        // 回退到 Chrome i18n API
        return chrome.i18n.getMessage(key);
    }

    // 当前缩放级别和位置
    let currentZoom = 1;
    let svgPosition = { x: 0, y: 0 };
    let isDragging = false;
    let dragStart = { x: 0, y: 0 };

    // Load last saved SVG code if any
    chrome.storage.local.get(['svgCode', 'svgZoom', 'svgPosition'], function(result) {
        if (result.svgCode) {
            svgCode.value = result.svgCode;
            renderSVG(result.svgCode);
        }
        if (result.svgZoom) {
            currentZoom = result.svgZoom;
            updateSvgZoom();
        }
        if (result.svgPosition) {
            svgPosition = result.svgPosition;
            updateSvgPosition();
        }
    });

    // 缩放控制
    zoomIn.addEventListener('click', function() {
        currentZoom += 0.1;
        updateSvgZoom();
        saveSvgZoom();
    });

    zoomOut.addEventListener('click', function() {
        currentZoom = Math.max(0.1, currentZoom - 0.1);
        updateSvgZoom();
        saveSvgZoom();
    });

    zoomReset.addEventListener('click', function() {
        currentZoom = 1;
        updateSvgZoom();
        saveSvgZoom();
    });

    // 重置位置按钮
    positionReset.addEventListener('click', function() {
        svgPosition = { x: 0, y: 0 };
        updateSvgPosition();
        saveSvgPosition();
        showNotification(getLocalizedMessage('positionReset'), 'success');
    });

    function updateSvgZoom() {
        const svg = svgOutput.querySelector('.svg-container svg');
        if (svg) {
            svg.style.transform = `translate(${svgPosition.x}px, ${svgPosition.y}px) scale(${currentZoom})`;
        }

        // 更新百分比显示
        const zoomPercentage = document.getElementById('zoom-percentage');
        if (zoomPercentage) {
            zoomPercentage.textContent = `${Math.round(currentZoom * 100)}%`;
        }
    }

    function updateSvgPosition() {
        const svg = svgOutput.querySelector('.svg-container svg');
        if (svg) {
            svg.style.transform = `translate(${svgPosition.x}px, ${svgPosition.y}px) scale(${currentZoom})`;
        }
    }

    function saveSvgZoom() {
        chrome.storage.local.set({ svgZoom: currentZoom });
    }

    function saveSvgPosition() {
        chrome.storage.local.set({ svgPosition: svgPosition });
    }

    // Tab switching
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 如果是全屏模式，不应用标签切换
            if (isInTab) return;

            const tabName = this.getAttribute('data-tab');

            // Update active tab
            tabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');

            // Show/hide content based on selected tab
            if (tabName === 'editor') {
                svgInput.classList.remove('hidden');
                svgOutput.classList.add('hidden');
            } else {
                svgInput.classList.add('hidden');
                svgOutput.classList.remove('hidden');
                renderSVG(svgCode.value);
            }
        });
    });

    // Preview button click handler
    previewBtn.addEventListener('click', function() {
        const code = svgCode.value.trim();

        if (!code) {
            showNotification(getLocalizedMessage('noSvgCode'), 'error');
            return;
        }

        // Save to storage
        chrome.storage.local.set({ svgCode: code });

        // Render SVG
        renderSVG(code);

        // 如果不是全屏模式，切换到预览标签
        if (!isInTab) {
            // Switch to preview tab
            tabs.forEach(t => t.classList.remove('active'));
            tabs[1].classList.add('active');
            svgInput.classList.add('hidden');
            svgOutput.classList.remove('hidden');
        }
    });

    // Paste button click handler
    pasteBtn.addEventListener('click', async function() {
        try {
            const text = await navigator.clipboard.readText();
            if (text.trim().startsWith('<svg') || text.trim().startsWith('<?xml')) {
                svgCode.value = text;
                showNotification(getLocalizedMessage('svgPasted'), 'success');
            } else {
                showNotification(getLocalizedMessage('invalidSvg'), 'error');
            }
        } catch (err) {
            showNotification(getLocalizedMessage('clipboardError'), 'error');
        }
    });

    // Copy button click handler
    copyBtn.addEventListener('click', async function() {
        const code = svgCode.value.trim();

        if (!code) {
            showNotification(getLocalizedMessage('nothingToCopy'), 'error');
            return;
        }

        try {
            await navigator.clipboard.writeText(code);
            showNotification(getLocalizedMessage('svgCopied'), 'success');
        } catch (err) {
            showNotification(getLocalizedMessage('copyError'), 'error');
        }
    });

    // Clear button click handler
    clearBtn.addEventListener('click', function() {
        svgCode.value = '';

        // Preserve zoom controls when clearing
        const zoomControls = svgOutput.querySelector('.zoom-controls');
        svgOutput.innerHTML = '';
        if (zoomControls) {
            svgOutput.appendChild(zoomControls);
        }

        currentZoom = 1;
        svgPosition = { x: 0, y: 0 };
        updateSvgZoom();
        chrome.storage.local.remove(['svgCode', 'svgZoom', 'svgPosition']);
        showNotification(getLocalizedMessage('cleared'), 'success');
    });

    // Render SVG function
    function renderSVG(code) {
        if (!code) return;

        try {
            // Basic validation
            if (!code.includes('<svg')) {
                throw new Error(getLocalizedMessage('invalidSvgCode'));
            }

            // Clear previous SVG but keep the zoom controls
            const zoomControls = svgOutput.querySelector('.zoom-controls');
            svgOutput.innerHTML = '';

            // Create a container for the SVG content
            const svgContainer = document.createElement('div');
            svgContainer.className = 'svg-container';
            svgContainer.innerHTML = code;

            // Append the SVG container first
            svgOutput.appendChild(svgContainer);

            // Append existing zoom controls if available or create new ones
            if (zoomControls) {
                svgOutput.appendChild(zoomControls);
            } else {
                const newZoomControls = document.createElement('div');
                newZoomControls.className = 'zoom-controls';
                newZoomControls.innerHTML = `
                    <div class="zoom-percentage" id="zoom-percentage">${Math.round(currentZoom * 100)}%</div>
                    <button class="zoom-btn" id="zoom-in">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>
                        </svg>
                    </button>
                    <button class="zoom-btn" id="zoom-out">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"/>
                        </svg>
                    </button>
                    <button class="zoom-btn" id="zoom-reset">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M8 3.5a.5.5 0 0 0-1 0V9a.5.5 0 0 0 .252.434l3.5 2a.5.5 0 0 0 .496-.868L8 8.71V3.5z"/>
                            <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm7-8A7 7 0 1 1 1 8a7 7 0 0 1 14 0z"/>
                        </svg>
                    </button>
                    <button class="zoom-btn" id="position-reset">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                            <path d="M7.646 2.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 3.707 2.354 9.354a.5.5 0 1 1-.708-.708l6-6z"/>
                            <path d="M7.646 6.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 7.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/>
                        </svg>
                    </button>
                `;
                svgOutput.appendChild(newZoomControls);
            }

            // 重新获取缩放按钮并添加事件监听
            const newZoomIn = document.getElementById('zoom-in');
            const newZoomOut = document.getElementById('zoom-out');
            const newZoomReset = document.getElementById('zoom-reset');
            const newPositionReset = document.getElementById('position-reset');

            newZoomIn.addEventListener('click', function() {
                currentZoom += 0.1;
                updateSvgZoom();
                saveSvgZoom();
            });

            newZoomOut.addEventListener('click', function() {
                currentZoom = Math.max(0.1, currentZoom - 0.1);
                updateSvgZoom();
                saveSvgZoom();
            });

            newZoomReset.addEventListener('click', function() {
                currentZoom = 1;
                updateSvgZoom();
                saveSvgZoom();
            });

            newPositionReset.addEventListener('click', function() {
                svgPosition = { x: 0, y: 0 };
                updateSvgPosition();
                saveSvgPosition();
                showNotification(getLocalizedMessage('positionReset'), 'success');
            });

            // Apply animations to the SVG
            const svg = svgOutput.querySelector('svg');
            if (svg) {
                svg.style.transition = 'all 0.3s ease';
                svg.style.animation = 'pulse 2s infinite';
                svg.style.transformOrigin = 'center center';
                updateSvgZoom();
                setupDragControls();
            }
        } catch (error) {
            svgOutput.innerHTML = `<div style="color: var(--error); padding: 20px;">${getLocalizedMessage('renderError')}${error.message}</div>`;
        }
    }

    // Show notification function
    function showNotification(message, type) {
        notification.textContent = message;
        notification.className = 'notification';
        notification.classList.add(type);
        notification.classList.add('show');

        setTimeout(() => {
            notification.classList.remove('show');
        }, 3000);
    }

    // Handle drag and drop
    svgInput.addEventListener('dragover', (e) => {
        e.preventDefault();
        svgInput.style.backgroundColor = 'rgba(99, 102, 241, 0.1)';
    });

    svgInput.addEventListener('dragleave', () => {
        svgInput.style.backgroundColor = '';
    });

    svgInput.addEventListener('drop', (e) => {
        e.preventDefault();
        svgInput.style.backgroundColor = '';

        const file = e.dataTransfer.files[0];
        if (file && file.type === 'image/svg+xml') {
            const reader = new FileReader();
            reader.onload = (event) => {
                svgCode.value = event.target.result;
                showNotification(getLocalizedMessage('svgFileLoaded'), 'success');
            };
            reader.readAsText(file);
        } else {
            showNotification(getLocalizedMessage('dragSvgFile'), 'error');
        }
    });

    // Keyboard shortcuts
    document.addEventListener('keydown', (e) => {
        // Ctrl+V or Command+V to paste
        if ((e.ctrlKey || e.metaKey) && e.key === 'v' && document.activeElement !== svgCode) {
            pasteBtn.click();
        }

        // Ctrl+C or Command+C to copy
        if ((e.ctrlKey || e.metaKey) && e.key === 'c' && document.activeElement !== svgCode) {
            copyBtn.click();
        }

        // F5 or Ctrl+R for preview
        if (e.key === 'F5' || ((e.ctrlKey || e.metaKey) && e.key === 'r')) {
            e.preventDefault();
            previewBtn.click();
        }
    });

    // Example SVG button for quick testing
    const exampleSvg = `<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" stop-color="#6366F1" />
      <stop offset="100%" stop-color="#EC4899" />
    </linearGradient>
  </defs>
  <circle cx="100" cy="100" r="80" fill="url(#gradient)" />
  <path d="M70 80 L130 80 L100 120 Z" fill="white" />
  <circle cx="80" cy="70" r="10" fill="white" />
  <circle cx="120" cy="70" r="10" fill="white" />
</svg>`;


    const exampleLink = document.querySelector('.example-link');
    // 示例链接点击处理
    exampleLink.addEventListener('click', function() {
        svgCode.value = exampleSvg;
        renderSVG(exampleSvg);
        showNotification(getLocalizedMessage('exampleLoaded'), 'success');
    });

    // 添加拖动功能
    function setupDragControls() {
        const svg = svgOutput.querySelector('.svg-container svg');
        if (!svg) return;

        svg.style.cursor = 'grab';

        svg.addEventListener('mousedown', startDrag);
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', endDrag);

        // 移动端支持
        svg.addEventListener('touchstart', startDrag);
        document.addEventListener('touchmove', drag);
        document.addEventListener('touchend', endDrag);

        function startDrag(e) {
            if (e.type.includes('touch')) {
                e.preventDefault();
                const touch = e.touches[0];
                dragStart.x = touch.clientX;
                dragStart.y = touch.clientY;
            } else {
                dragStart.x = e.clientX;
                dragStart.y = e.clientY;
            }
            isDragging = true;
            svg.style.cursor = 'grabbing';
        }

        function drag(e) {
            if (!isDragging) return;

            let clientX, clientY;
            if (e.type.includes('touch')) {
                const touch = e.touches[0];
                clientX = touch.clientX;
                clientY = touch.clientY;
            } else {
                clientX = e.clientX;
                clientY = e.clientY;
            }

            const dx = clientX - dragStart.x;
            const dy = clientY - dragStart.y;

            svgPosition.x += dx;
            svgPosition.y += dy;

            updateSvgPosition();

            dragStart.x = clientX;
            dragStart.y = clientY;
        }

        function endDrag() {
            if (!isDragging) return;
            isDragging = false;
            svg.style.cursor = 'grab';
            saveSvgPosition();
        }
    }
});